package com.dmzc.stage2.chapter19;

import com.dmzc.stage2.chapter19.Task;

import java.util.concurrent.atomic.AtomicInteger;

public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {

    private final static String FUTURE_THREAD_PREFIX = "FUTURE-";
    private final AtomicInteger nextCounter = new AtomicInteger(0);

    private String getNextName() {
        return FUTURE_THREAD_PREFIX + nextCounter.getAndIncrement();
    }

    /**
     * 提交不需要返回值的任务
     *
     * @param runnable
     * @return
     */
    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Void> future = new FutureTask<>();
        new Thread(() -> {
            runnable.run();
            future.finish(null);
        }).start();
        return future;
    }

    /**
     * 提交需要返回值的任务
     *
     * @param task
     * @param input
     * @return
     */
    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            future.finish(result);
        }, getNextName()).start();
        return future;
    }

    /**
     * 增加回调
     *
     * @param task
     * @param input
     * @param callback
     * @return
     */
    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input, Callback<OUT> callback) {
        final FutureTask<OUT>future=new FutureTask<>();
        new Thread(()->{
            OUT result=task.get(input);
            future.finish(result);
            if (null!=callback)
                callback.call(result);
        },getNextName()).start();
        return future;
    }


}
